package com.binguo.helper;


import com.binguo.model.mapper.ShopMapper;
import com.binguo.model.model.Shop;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
// 导入对应产品模块的client
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.cvm.v20170312.CvmClient;
// 导入要请求接口对应的request response类
import com.tencentcloudapi.cvm.v20170312.models.DescribeZonesRequest;
import com.tencentcloudapi.cvm.v20170312.models.DescribeZonesResponse;
import com.tencentcloudapi.iai.v20180301.IaiClient;
import com.tencentcloudapi.iai.v20180301.models.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FaceHelperV3 implements InitializingBean {

    private static final String secretId = "AKIDud6KAoFVVHrDLFCLYXIp8B0aCZpql7NN";
    private static final String secretKey = "tXv3wZ0B9sMwNacR2PYUCftsfDk49yYs";

    private static IaiClient client;

    static {
        Credential cred = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("iai.tencentcloudapi.com");

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        client = new IaiClient(cred, "ap-shanghai", clientProfile);
    }

    public static void main(String[] args) {
//        CreateGroup();
//        CreatePerson();
//        SearchFaces();
//        DetectFace();
//        CompareFace();'
//        DetectLiveFace();
//        VerifyFace();
//        CreateFace();

        /*if (!isShopExist("87")) {
            createGroup("87");
        }*/

        detectFace(23,"http://img.binguoai.com/4587171d3ae69521.jpeg");

        /**
         * {"shopId":63,"faceUrl":"http://img.binguoai.com/63__POS_1.9.1_5008211630603003153.jpg"}
         * {"shopId":62,"faceUrl":"http://img.binguoai.com/62__POS_1.6.1_5004026827226189242.jpg"}
         * [TencentCloudSDKException]message:FailedOperation.ImageDownloadError-图片下载错误。 requestId:a9bc830c-6568-4094-afe4-e301dc96ef7c
         */
    /*    long s = System.currentTimeMillis();
        System.out.println(s);
        searchFacesFromSingleShop("http://img.binguoai.com/WechatIMG134.jpeg" +
                "", "133");

        getPersonBaseInfo("128_12899");
        getPersonBaseInfo("133_12899");
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis() - s);*/
    }




    /**
     * 创建人员库
     * @param shopId 传shopId
     * @return true:成功 false失败
     */
    public static boolean isShopExist(String shopId){
        try {
            String getGroupParams = "{}";
            GetGroupListRequest getGroupListRequest = GetGroupListRequest.
                    fromJsonString(getGroupParams, GetGroupListRequest.class);

            GetGroupListResponse getGroupListResponse = client.GetGroupList(getGroupListRequest);

            System.out.println(GetGroupListRequest.toJsonString(getGroupListResponse));

            GroupInfo[] groupInfos = getGroupListResponse.getGroupInfos();
            if (groupInfos != null && groupInfos.length > 0) {
                for (GroupInfo groupInfo : groupInfos) {
                    if (groupInfo.getGroupId().equals(shopId)) {
                        return true;
                    }
                }

                return false;
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * 创建人员库
     * @param shopId 传shopId
     * @return true:成功 false失败
     */
    public static boolean createGroup(String shopId){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.createGroup(shopId, intranetShopIdList.get(Integer.valueOf(shopId)));
        }

        try{
            String getGroupParams = "{}";
            GetGroupListRequest getGroupListRequest = GetGroupListRequest.fromJsonString(getGroupParams, GetGroupListRequest.class);

            GetGroupListResponse getGroupListResponse = client.GetGroupList(getGroupListRequest);

            System.out.println(GetGroupListRequest.toJsonString(getGroupListResponse));

            GroupInfo[] groupInfos = getGroupListResponse.getGroupInfos();
            if (groupInfos != null && groupInfos.length > 0) {
                for (GroupInfo groupInfo : groupInfos) {
                    if (groupInfo.getGroupId().equals(shopId)) {
                        return true;
                    }
                }
            }


            String params = "{\"GroupName\":\"yunpeng" + shopId + "\",\"GroupId\":\"" + shopId + "\"}";
            CreateGroupRequest req = CreateGroupRequest.fromJsonString(params, CreateGroupRequest.class);

            CreateGroupResponse resp = client.CreateGroup(req);

            System.out.println(CreateGroupRequest.toJsonString(resp));

            return true;
            /**
             * {"RequestId":"d6c4b9df-c011-4cb5-8789-3fc936eaf012"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());

        }

        return false;
    }

    /**
     * 创建人员
     * personId 为groupId_customerId,确保唯一性
     * @param shopId 传shopId
     * @param personId 传personId
     * @param faceUrl 传人脸图片地址
     * @return faceId
     */
    public static String createPerson(String shopId, String personId, String faceUrl){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.createPerson(shopId, personId, faceUrl, intranetShopIdList.get(Integer.valueOf(shopId)));
        }

        try{
            String params = "{\"GroupId\":\"" + shopId + "\",\"PersonName\":\"" +
                    personId + "\",\"PersonId\":\"" + personId + "\",\"Url\":\"" + faceUrl + "\"}";
            CreatePersonRequest req = CreatePersonRequest.fromJsonString(params, CreatePersonRequest.class);

            CreatePersonResponse resp = client.CreatePerson(req);

            System.out.println(CreatePersonRequest.toJsonString(resp));

            return resp.getFaceId();
            /**
             * {"FaceId":"3143837819458322303","RequestId":"2c1a386a-dcb0-4c47-9f69-91c65f713069"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return null;
    }

    /**
     * 删除人脸
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceId 传创建人脸时返回的faceId值
     * @return true:成功 false:失败
     */
    public static boolean deleteFace(String personId, String faceId){
        String shopId = personId.split("_")[0];
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.deleteFace(personId, faceId, intranetShopIdList.get(Integer.valueOf(shopId)));
        }

        try{
            String params = "{\"PersonId\":\"" + personId + "\",\"FaceIds\":[\"" + faceId + "\"]}";
            DeleteFaceRequest req = DeleteFaceRequest.fromJsonString(params, DeleteFaceRequest.class);

            DeleteFaceResponse resp = client.DeleteFace(req);

            System.out.println(DeleteFaceRequest.toJsonString(resp));

            return true;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return false;

    }

    /**
     * 删除人员库
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @return true:成功 false:失败
     */
    public static boolean deleteGroup(String shopId){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.deleteGroup(shopId, intranetShopIdList.get(Integer.valueOf(shopId)));
        }

        try{
            String params = "{\"GroupId\":\"" + shopId + "\"}";
            DeleteGroupRequest req = DeleteGroupRequest.fromJsonString(params, DeleteGroupRequest.class);

            DeleteGroupResponse resp = client.DeleteGroup(req);

            System.out.println(DeleteGroupRequest.toJsonString(resp));

            return true;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return false;
    }

    /**
     * 删除人员(在不知道人员所属商户的情况下使用此方法)
     * personId 为groupId_customerId,确保唯一性
     * @param personId
     * @return true:成功 false:失败
     */
    public static boolean deletePerson(String personId){
        String shopId = personId.split("_")[0];
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.deletePerson(personId, intranetShopIdList.get(Integer.valueOf(shopId)));
        }
        try{
            String params = "{\"PersonId\":\"" + personId + "\"}";
            DeletePersonRequest req = DeletePersonRequest.fromJsonString(params, DeletePersonRequest.class);

            DeletePersonResponse resp = client.DeletePerson(req);

            System.out.println(DeletePersonRequest.toJsonString(resp));

            return true;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return false;

    }

    /**
     * 人员库删除人员
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @param customerId
     * @return true:成功 false:失败
     */
    public static boolean deletePersonFromShop(String shopId, String personId){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.deletePersonFromShop(shopId, personId, intranetShopIdList.get(Integer.valueOf(shopId)));
        }

        try{
            String params = "{\"PersonId\":\"" + personId + "\",\"GroupId\":\"" + shopId + "\"}";
            DeletePersonFromGroupRequest req = DeletePersonFromGroupRequest.fromJsonString(params, DeletePersonFromGroupRequest.class);

            DeletePersonFromGroupResponse resp = client.DeletePersonFromGroup(req);

            System.out.println(DeletePersonFromGroupRequest.toJsonString(resp));

            return true;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return false;
    }

    /**
     * 获取人员基础信息
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @return GetPersonBaseInfoResponse
     */
    public static GetPersonBaseInfoResponse getPersonBaseInfo(String customerId){
        String shopId = customerId.split("_")[0];
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.getPersonBaseInfo(customerId, intranetShopIdList.get(Integer.valueOf(shopId)));
        }
        try{
            String params = "{\"PersonId\":\"" + customerId + "\"}";
            GetPersonBaseInfoRequest req = GetPersonBaseInfoRequest.fromJsonString(params, GetPersonBaseInfoRequest.class);

            GetPersonBaseInfoResponse resp = client.GetPersonBaseInfo(req);

            System.out.println(GetPersonBaseInfoRequest.toJsonString(resp));

            return resp;
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return null;
    }

    /**
     * 获取人员列表
     * personId 为groupId_customerId,确保唯一性
     * @param shopId
     * @param offset 第几个结果集开始查
     * @param limit 查询多少个
     * @return faceId
     */
    public static PersonInfo[] getPersonList(String shopId, Integer offset, Integer limit){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.getPersonList(shopId, offset, limit, intranetShopIdList.get(Integer.valueOf(shopId)));
        }
        try{
            String params = "{\"GroupId\":\"" + shopId + "\",\"Offset\":" + offset + ",\"Limit\":" + limit + "}";
            GetPersonListRequest req = GetPersonListRequest.fromJsonString(params, GetPersonListRequest.class);

            GetPersonListResponse resp = client.GetPersonList(req);

            System.out.println(GetPersonListRequest.toJsonString(resp));

            return resp.getPersonInfos();
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return null;

    }

    /**
     * 人脸搜索
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @param shopId
     * @return 查询结果集
     */
    public static Result[] searchFacesFromSingleShop(String faceUrl, String shopId){
        return searchFacesFromMultiple(faceUrl, new String[]{shopId});
    }

    /**
     * 人脸搜索
     * @param faceUrl
     * @param shopId
     * @return 查询结果集
     */
    public static Result[] searchFacesFromMultiple(String faceUrl, String[] shopId){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId[0]))) {
            return FaceHelperV5.searchFacesFromMultiple(faceUrl, shopId, intranetShopIdList.get(Integer.valueOf(shopId[0])));
        }

        try{
            String params = null;
            if (shopId.length > 1) {
                params = "{\"GroupIds\":[";
                for (String shopIdTemp : shopId) {
                    params += "\"" + shopIdTemp + "\",";
                }
                //减去最后一个,逗号
                params = params.substring(0, params.length() - 1);

                params += "],\"Url\":\"" + faceUrl + "\"}";
            } else {
                params = "{\"GroupIds\":[\"" + shopId[0] + "\"],\"Url\":\"" + faceUrl + "\"}";
            }
            SearchFacesRequest req = SearchFacesRequest.fromJsonString(params, SearchFacesRequest.class);

            SearchFacesResponse resp = client.SearchFaces(req);

            System.out.println(SearchFacesRequest.toJsonString(resp));

            return resp.getResults();
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return null;
    }

    /**
     * 人脸检测与分析
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @return 人脸图片质量分
     */
    public static int detectFace(Integer shopId, String faceUrl){
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.detectFace(shopId, faceUrl, intranetShopIdList.get(Integer.valueOf(shopId)));
        }
        try{
            String params = "{\"Url\":\"" + faceUrl + "\",\"NeedQualityDetection\":1}";
            DetectFaceRequest req = DetectFaceRequest.fromJsonString(params, DetectFaceRequest.class);

            DetectFaceResponse resp = client.DetectFace(req);

            System.out.println(DetectFaceRequest.toJsonString(resp));
            System.out.println(resp.getFaceInfos()[0].getFaceQualityInfo().getScore());

            return resp.getFaceInfos()[0].getFaceQualityInfo().getScore().intValue();
            /**
             * {"ImageWidth":1080,"ImageHeight":720,"FaceInfos":[{"X":390,"Y":259,"Width":370,"Height":370,"FaceAttributesInfo":{"Gender":0,"Age":0,"Expression":0,"Glass":false,"Pitch":0,"Yaw":0,"Roll":0,"Beauty":0,"Hat":false,"Mask":false,"Hair":{"Length":0,"Bang":0,"Color":0},"EyeOpen":false},"FaceQualityInfo":{"Score":79,"Sharpness":79,"Brightness":43,"Completeness":{"Eyebrow":99,"Eye":99,"Nose":99,"Cheek":99,"Mouth":99,"Chin":99}}}],"RequestId":"936e8632-2c0b-4b0a-b387-ca9ab3eb4055"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return 0;

    }

    /**
     * @Author: yujing
     * @Description:
     * @param base64
     * @DateTime: 2020/5/29 15:26
     * @Return int
     */
    public static int detectFaceBase64(String base64){

        try{
            String params = "{\"Image\":\"" + base64 + "\",\"NeedQualityDetection\":1}";
            DetectFaceRequest req = DetectFaceRequest.fromJsonString(params, DetectFaceRequest.class);

            DetectFaceResponse resp = client.DetectFace(req);

            System.out.println(DetectFaceRequest.toJsonString(resp));
            System.out.println(resp.getFaceInfos()[0].getFaceQualityInfo().getScore());

            return resp.getFaceInfos()[0].getFaceQualityInfo().getScore().intValue();
            /**
             * {"ImageWidth":1080,"ImageHeight":720,"FaceInfos":[{"X":390,"Y":259,"Width":370,"Height":370,"FaceAttributesInfo":{"Gender":0,"Age":0,"Expression":0,"Glass":false,"Pitch":0,"Yaw":0,"Roll":0,"Beauty":0,"Hat":false,"Mask":false,"Hair":{"Length":0,"Bang":0,"Color":0},"EyeOpen":false},"FaceQualityInfo":{"Score":79,"Sharpness":79,"Brightness":43,"Completeness":{"Eyebrow":99,"Eye":99,"Nose":99,"Cheek":99,"Mouth":99,"Chin":99}}}],"RequestId":"936e8632-2c0b-4b0a-b387-ca9ab3eb4055"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return 0;

    }

    /**
     * 人脸比对
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrlSource
     * @param faceUrlTarget
     * @return 对比分数
     */
    public static float compareFace(String faceUrlSource, String faceUrlTarget){
        try{

            Credential cred = new Credential(secretId, secretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("iai.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            IaiClient client = new IaiClient(cred, "ap-shanghai", clientProfile);

            String params = "{\"UrlA\":\"" + faceUrlSource + "\",\"UrlB\":\"" + faceUrlTarget + "\"}";
            CompareFaceRequest req = CompareFaceRequest.fromJsonString(params, CompareFaceRequest.class);

            CompareFaceResponse resp = client.CompareFace(req);

            System.out.println(CompareFaceRequest.toJsonString(resp));

            return resp.getScore();
            /**
             * {"Score":100.0,"RequestId":"a39cf2a7-4568-4952-a300-9db4b2b65ecf"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }


        return 0;

    }

    /**
     * 人脸静态活体检测
     * personId 为groupId_customerId,确保唯一性
     * @param faceUrl
     * @return 检测结果分数
     */
    public static float detectLiveFace(String faceUrl){
        try{
            String params = "{\"Url\":\"" + faceUrl + "\"}";
            DetectLiveFaceRequest req = DetectLiveFaceRequest.fromJsonString(params, DetectLiveFaceRequest.class);

            DetectLiveFaceResponse resp = client.DetectLiveFace(req);

            System.out.println(DetectLiveFaceRequest.toJsonString(resp));

            return resp.getScore();
            /**
             * {"Score":0.0,"RequestId":"fc699b64-7336-4196-acef-264ffb485628"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }


        return 0;
    }

    /**
     * 人脸验证
     * personId 为groupId_customerId,确保唯一性
     * @param personId
     * @param faceUrl
     * @return true:匹配 false:不匹配
     */
    public static boolean VerifyFace(String personId, String faceUrl){
        try{

            String params = "{\"Url\":\"" + faceUrl + "\",\"PersonId\":\"" + personId + "\"}";
            VerifyFaceRequest req = VerifyFaceRequest.fromJsonString(params, VerifyFaceRequest.class);

            VerifyFaceResponse resp = client.VerifyFace(req);

            System.out.println(VerifyFaceRequest.toJsonString(resp));

            return resp.getIsMatch();
            /**
             * {"Score":100.0,"IsMatch":true,"RequestId":"24fb129f-7787-49e2-9be9-24551d5443d7"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return false;

    }

    /**
     * 增加人脸
     * personId 为groupId_customerId,确保唯一性
     * @param customerId
     * @param faceUrl
     * @return true:成功 false:失败
     */
    public static String addFace(String customerId, String faceUrl){
        String shopId = customerId.split("_")[0];
        if (intranetShopIdList.containsKey(Integer.valueOf(shopId))) {
            return FaceHelperV5.addFace(customerId, faceUrl, intranetShopIdList.get(Integer.valueOf(shopId)));
        }
        try{
            String params = "{\"PersonId\":\"" + customerId + "\",\"Urls\":[\"" + faceUrl + "\"]}";
            CreateFaceRequest req = CreateFaceRequest.fromJsonString(params, CreateFaceRequest.class);

            CreateFaceResponse resp = client.CreateFace(req);

            System.out.println(CreateFaceRequest.toJsonString(resp));

            if (resp.getRetCode()[0] == 0) {
                return resp.getSucFaceIds()[0];
            }
            /**
             * {"SucFaceNum":1,"SucFaceIds":["3143865174221444978"],"RetCode":[0],"RequestId":"4fe93b3e-b2ee-470c-8c52-e157cea59483"}
             */
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

        return null;
    }

    @Resource
    private ShopMapper shopMapper;

    public static Map<Integer, String> intranetShopIdList = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        List<Shop> shopList = shopMapper.selectAll();
        for (Shop shop : shopList) {
            if (StringUtils.hasText(shop.getIntranetFaceaddress())) {
                intranetShopIdList.put(shop.getId(), shop.getIntranetFaceaddress());
            }
        }
    }
}
